Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
Function returning "undefined" while trying to query database in node.js

This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!

var funcs = require('./index.js');
var connected = require('./database')

query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)


function execute_rows(query){
 con = connected();
 con.query(query, function(err, result, fields) {
     if (err) {
         return console.log(err);
     }
     console.log(result) //Displays correct results
     return result; // Returns undefined to calling function
 })
 con.end();
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Harshith

Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.

The problem with your function is your not actually returning the result "on time". You need to return a promise to get the result from your function.

This could be a little hard to understand when you're new in JS. Your function should be something like this:

function execute_rows(query){
 con = connected();
 return new Promise((resolve, reject) => {
     con.query(query, function(err, result, fields) {
         if (err) {
             // Returning the error
             reject(err);
             con.end();
         }

         resolve(result);
         con.end();
     });
 });
}

Now, when you call you call your function, you have two options:

  1. Use async/await
  2. Still using promises (callback-driven)

Calling your function:

const dbResult = await execute_rows(query);

or

execute_rows(query).then(result => {
    // Get the result
    console.log('result:', result);
}).catch(error => {
    // Get the error
    console.log('error:', error);
});

Please, read about promises and async/await pattern! Links:

Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda